import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/project/response/ListProjectResponse.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';

import 'state.dart';

class ProjectScreenLogic extends GetxController {
  final ProjectScreenState state = ProjectScreenState();

  Future<void> refreshProjectPage() async {
    getListByStatus();
  }

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  void _initData() {
    _getListProject();
  }

  void _getListProject() {
    MyHttpClient.getMyProject(null, null, null, null, null).then((value) {
      if (value.code == 200) {
        if (value.data!.records != null) {
          state.listProject.value = value.data!.records!;
        }
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void seeMore(Records records) {
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteProject(records),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteProject.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteProject(Records records) {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteProject.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        middleText: "${MyText.delete.tr}  ${records.name!} ?",
        middleTextStyle: Theme.of(Get.context!).textTheme.bodyLarge,
        onConfirm: () {
          Get.back();
          _realDelete(records);
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _realDelete(Records records) {
    LoadingElement.loadingDialog(true);
    MyHttpClient.deleteProject(records.id!).then((value) {
      if (value.code == 200) {
        Get.back();
        refreshProjectPage();
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  double getProgress(Records? listProject) {
    if (listProject == null || listProject.totalDemand == 0) {
      return 0;
    }
    if (listProject.totalDemand == null || listProject.finishDemand == null) {
      return 1;
    }
    return listProject.finishDemand! / listProject.totalDemand!;
  }

  String getFinishDay(Records? listProject) {
    if (listProject == null) {
      return MyText.xDayLeft.trParams({'x': '0'});
    }
    var now = DateTime.now();
    var end = DateTime.parse(listProject.endTime ?? "2001-03-18 06:18:43");
    if (now.isAfter(end)) {
      return MyText.xDayLeft.trParams({'x': '0'});
    }
    var difference = end.difference(now);
    return MyText.xDayLeft.trParams({'x': difference.inDays.toString()});
  }

  Color getMainColor(Records? listProject) {
    if (listProject == null) {
      return state.listColor[0];
    }
    var index = listProject.id?.toInt() ?? 0;
    return state.listColor[index % 4];
  }

  getBg(Records? listProject) {
    if (listProject == null) {
      return AssetImage(state.listBg[Random().nextInt(99) % 4]);
    }
    if (listProject.backgroundUrl == null ||
        listProject.backgroundUrl!.isEmpty) {
      return AssetImage(state.listBg[listProject.id!.toInt() % 4]);
    }
    return NetworkImage(listProject.backgroundUrl!);
  }

  getLogo(Records? listProject) {
    if (listProject == null) {
      return AssetImage(state.listBg[Random().nextInt(99) % 4]);
    }
    if (listProject.logoUrl == null || listProject.logoUrl!.isEmpty) {
      return AssetImage(state.listBg[(listProject.id!.toInt() + 1) % 4]);
    }
    return NetworkImage(listProject.backgroundUrl!);
  }

  void getListByStatus() {
    LoadingElement.loadingDialog(true);
    if (state.selectValue.value == 0) {
      MyHttpClient.getMyProject(null, null, null, null, null).then((value) {
        if (value.code == 200) {
          if (value.data!.records != null) {
            state.listProject.value = value.data!.records!;
            Get.back();
          }
        } else {
          Utils.toastError(value.msg);
        }
      }).onError((error, stackTrace) {
        Utils.toastError(error);
      });
      return;
    }
    MyHttpClient.getMyProject(
            null, null, null, state.selectValue.value.toString(), null)
        .then((value) {
      if (value.code == 200) {
        if (value.data!.records != null) {
          state.listProject.value = value.data!.records!;
          Get.back();
        }
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void jumpToDetail(Records listProject) {
    Get.toNamed(RouteConfig.projectDetailScreen,
        arguments: {'projectId': listProject.id, 'pid': 0});
  }
}
